import Vue from 'vue'
import axios from 'axios'
import { message } from '../plugin/element'

axios.defaults.baseURL = '/api'

axios.interceptors.response.use((res) => {
  return res.data
}, (err) => {
  if (err.response) {
    const response = err.response
    console.log(err.response)
    message.error(response.statusText)
  }
  return Promise.reject(err)
})

class Http {
  request (ops) {
    return axios.request(ops)
  }

  get (url, params, ops) {
    return this.request({
      url,
      ...ops,
      params,
      options: ops
    })
  }

  post (url, data, ops) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...ops
    })
  }

  put (url, data, ops) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...ops
    })
  }

  patch (url, data, ops) {
    return this.request({
      url,
      method: 'PATCH',
      data,
      ...ops
    })
  }

  delete (url, data, ops) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...ops
    })
  }

  cancelToken (url, data, ops) {
    let token = axios.CancelToken
    return token.source()
  }
}

export const http = new Http()

Vue.prototype.$http = http
